package constant.milk.cashbook.sms;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;

import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import constant.milk.cashbook.R;
import constant.milk.cashbook.SuperActivity;
import constant.milk.cashbook.asset.MemoActivity;
import constant.milk.cashbook.asset.MoneyActivity;
import constant.milk.cashbook.bean.BankData;
import constant.milk.cashbook.bean.CheckData;
import constant.milk.cashbook.bean.CreditData;
import constant.milk.cashbook.bean.GiftData;
import constant.milk.cashbook.bean.PhoneData;
import constant.milk.cashbook.bean.RealData;
import constant.milk.cashbook.bean.SmsData;
import constant.milk.cashbook.bean.SmsInputData;
import constant.milk.cashbook.category.CategoryMainListActivity;
import constant.milk.cashbook.category.CategorySubListActivity;
import constant.milk.cashbook.database.DBSelectQuery;
import constant.milk.cashbook.database.DbDeleteQuery;
import constant.milk.cashbook.database.DbInsertQuery;
import constant.milk.cashbook.database.DbUpdateQuery;
import constant.milk.cashbook.insert.AssetChoiceActivity;
import constant.milk.cashbook.insert.AssetListActivity;
import constant.milk.cashbook.insert.InsertActivity;
import constant.milk.cashbook.sms.parser.SmsParser;
import constant.milk.cashbook.tip.TipInfoActivity;
import constant.milk.cashbook.tip.TipMap;
import constant.milk.cashbook.util.CalendarActivity;
import constant.milk.cashbook.util.MilkManager;
import constant.milk.cashbook.util.MilkUtil;
import constant.milk.cashbook.util.TimeActivity;

public class SmsInfoActivity extends SuperActivity
{
	public static final String SMS_ID = "SMS_ID";
	
	public static final int ASSET_CHOICE_REQUEST_CODE = 0;
	public static final int ASSET_LIST_REQUEST_CODE = 1;
	public static final int REALMONEY_LIST_REQUEST_CODE = 2;
	
	private TextView typeTextView;
	private TextView telTextView;
	private TextView assetTextView;
	
	private View linkAssetView;
	private TextView linkAssetTextView;
	
	private View linkAssetNameView;
	private TextView linkAssetNameTextView;
	
	private View realMoneyNameView;
	private TextView realMoneyNameTextView;
	
	private Button deleteButton;
	private Button updateButton;
	
	private ArrayList<String> assetNameList;
	private ArrayList<String> realMoneyNameList;
	
	private MilkManager milkManager;
	
	private SmsData data;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.sms_info_activity);
		
		setTitle("문자정보");
		
		setFindViewId();
		setOnClick();
		setData();
	}

	@Override
	protected void setFindViewId()
	{
		typeTextView = (TextView) findViewById(R.id.smsInfoTypeTextView);
		telTextView = (TextView) findViewById(R.id.smsInfoTelTextView);
		assetTextView = (TextView) findViewById(R.id.smsInfoAssetTextView);
		
		linkAssetView = findViewById(R.id.smsInfoLinkAssetView);
		linkAssetTextView = (TextView) findViewById(R.id.smsInfoLinkAssetTextView);
		
		linkAssetNameView = findViewById(R.id.smsInfoLinkAssetNameView);
		linkAssetNameTextView = (TextView) findViewById(R.id.smsInfoLinkAssetNameTextView);
		
		realMoneyNameView = findViewById(R.id.smsInfoRealMoneyNameView);
		realMoneyNameTextView = (TextView) findViewById(R.id.smsInfoRealMoneyNameTextView);
		
		deleteButton = (Button) findViewById(R.id.deleteButton);
		updateButton = (Button) findViewById(R.id.updateButton);
	}

	@Override
	protected void setOnClick()
	{
		linkAssetView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(superContext, SmsAssetActivity.class);
				intent.putExtra(SmsAssetActivity.ASSET_CHOICE_DATA, linkAssetTextView.getText().toString());
				startActivityForResult(intent, ASSET_CHOICE_REQUEST_CODE);
			}
		});
		
		linkAssetNameView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				startAssetNameList();
			}
		});
		
		realMoneyNameView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				startRealMoneyNameList();
			}
		});
		
		deleteButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				if (setDeleteData())
				{
					MilkUtil.showDialogFinish(superContext, "확인", "데이터 삭제에 성공하였습니다.");
				}
				else
				{
					MilkUtil.showDialog(superContext, "실패", "잠시후 다시해 주세요.");
				}
			}
		});
		
		updateButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				if (!checkInsert())
				{
					return;
				}
				
				if (setUpdateData())
				{
					MilkUtil.showDialogFinish(superContext, "확인", "데이터 저장에 성공하였습니다.");
				}
				else
				{
					MilkUtil.showDialog(superContext, "실패", "잠시후 다시해 주세요.");
				}
			}
		});
	}

	@Override
	protected void setData()
	{
		DBSelectQuery select = new DBSelectQuery(superContext, superDb);
		milkManager = new MilkManager(superContext, superDb);
		
		Intent intent = getIntent();
		
		String id = intent.getStringExtra(SMS_ID);
		
		data = select.getSmsId(id);
		
		String typeString = "";
		
		switch (Integer.parseInt(data.getType()))
		{
			case SmsParser.IN_SMS:
				typeString = "수입";
				realMoneyNameView.setVisibility(View.GONE);
				break;
			case SmsParser.OUT_SMS:
				typeString = "지출";
				realMoneyNameView.setVisibility(View.GONE);
				break;
			case SmsParser.IN_ATM_SMS:
				typeString = "이동";
				realMoneyNameView.setVisibility(View.VISIBLE);
				break;
			case SmsParser.OUT_ATM_SMS:
				typeString = "이동";
				realMoneyNameView.setVisibility(View.VISIBLE);
				break;
			default:
				break;
		}
		
		typeTextView.setText(typeString);
		telTextView.setText(data.getAddress());
		assetTextView.setText(data.getName());
		
		linkAssetTextView.setText(milkManager.getAssetId(data.getAsset()));
		setAssetNameData(linkAssetTextView.getText().toString());
		
		linkAssetNameTextView.setText(data.getCardname());
		
		setRealMoneyNameData();
		
		if (data.getSubCardname() != null)
		{
			realMoneyNameTextView.setText(data.getSubCardname());
		}
	}
	
	private boolean checkInsert()
	{
		if (linkAssetNameTextView.getText().toString().equals(""))
		{
			MilkUtil.showToast(superContext, "자산을 추가해 주세요.");
			return false;
		}
		
		if (telTextView.getText().toString().equals(""))
		{
			MilkUtil.showToast(superContext, "전화번호가 정확하지 않습니다. 개발자에게 문자 내용을 메일로 보내주세요.");
			return false;
		}
		
		if (assetTextView.getText().toString().equals(""))
		{
			MilkUtil.showToast(superContext, "분석이름이 정확하지 않습니다. 개발자에게 문자 내용을 메일로 보내주세요.");
			return false;
		}
		
		if (linkAssetNameTextView.getText().toString().equals(""))
		{
			MilkUtil.showToast(superContext, "연결 자산이 없습니다. 자산관리에서 자산을 추가해주세요.");
			return false;
		}
		
		if (realMoneyNameView.getVisibility() == View.VISIBLE)
		{
			if (realMoneyNameTextView.getText().toString().equals(""))
			{
				MilkUtil.showToast(superContext, "연결 현금이 없습니다. 자산관리에서 현금을 추가해주세요.");
				return false;
			}
		}
		
		return true;
	}
	
	private boolean setDeleteData()
	{
		DbDeleteQuery query = null;
		try
		{
			query = new DbDeleteQuery(superContext, superDb);
			
			query.setBeginTansaction();
			
			query.setSmsDelete(data.getId());
			
			query.setSuccessful();
		} catch (Exception e)
		{
			e.printStackTrace();
			return false;
		} finally {
			try
			{
				query.setEndTansaction();
			} catch (Exception e)
			{
				e.printStackTrace();
				return false;
			}
		}
		
		return true;
	}
	
	private boolean setUpdateData()
	{
		DbUpdateQuery query = null;
		
		try
		{
			query = new DbUpdateQuery(superContext, superDb);
			
			query.setBeginTansaction();
			
			HashMap<String, String> map = new HashMap<String, String>();
			
			if (Integer.parseInt(data.getType()) == SmsParser.OUT_ATM_SMS)
			{
				map.put("cardname", linkAssetNameTextView.getText().toString());
				map.put("asset", milkManager.getAssetStr(linkAssetTextView.getText().toString()));
				map.put("subcardname", realMoneyNameTextView.getText().toString());
				map.put("subasset", milkManager.getAssetStr(getString(R.string.realAsset)));
			}
			else if (Integer.parseInt(data.getType()) == SmsParser.IN_ATM_SMS)
			{
				map.put("subcardname", linkAssetNameTextView.getText().toString());
				map.put("subasset", milkManager.getAssetStr(linkAssetTextView.getText().toString()));
				map.put("cardname", realMoneyNameTextView.getText().toString());
				map.put("asset", milkManager.getAssetStr(getString(R.string.realAsset)));
			}
			else if (Integer.parseInt(data.getType()) == SmsParser.OUT_SMS)
			{
				map.put("cardname", linkAssetNameTextView.getText().toString());
				map.put("asset", milkManager.getAssetStr(linkAssetTextView.getText().toString()));
			}
			else if (Integer.parseInt(data.getType()) == SmsParser.IN_SMS)
			{
				map.put("cardname", linkAssetNameTextView.getText().toString());
				map.put("asset", milkManager.getAssetStr(linkAssetTextView.getText().toString()));
			}
			
			query.setSmsUpdate(map, data.getId());
			
			query.setSuccessful();
		} catch (Exception e)
		{
			e.printStackTrace();
			return false;
		} finally {
			try
			{
				query.setEndTansaction();
			} catch (Exception e)
			{
				e.printStackTrace();
				return false;
			}
		}
		
		return true;
	}
	
	private void startAssetNameList()
	{
		Intent intent = new Intent(superContext, AssetListActivity.class);
		intent.putExtra(AssetListActivity.ASSET_NAME_DATA, linkAssetNameTextView.getText().toString());
		intent.putExtra(AssetListActivity.ASSET_TYPE_DATA, linkAssetTextView.getText().toString());
		startActivityForResult(intent, ASSET_LIST_REQUEST_CODE);
	}
	
	private void startRealMoneyNameList()
	{
		Intent intent = new Intent(superContext, AssetListActivity.class);
		intent.putExtra(AssetListActivity.ASSET_NAME_DATA, realMoneyNameTextView.getText().toString());
		intent.putExtra(AssetListActivity.ASSET_TYPE_DATA, getString(R.string.realAsset));
		startActivityForResult(intent, ASSET_LIST_REQUEST_CODE);
	}
	
	private void setAssetNameData(String str)
	{
		DBSelectQuery query = new DBSelectQuery(superContext, superDb);
		
		assetNameList = new ArrayList<String>();
		
		if (str.equals(getString(R.string.realAsset)))
		{
			ArrayList<RealData> list = query.getRealList();
			
			if (list == null || list.size() < 1)
			{
				linkAssetNameTextView.setText("");
				linkAssetNameTextView.setHint("현금을 추가해주세요.");
				return;
			}
			
			linkAssetNameTextView.setText(list.get(0).getName());
			
			for (int i = 0; i < list.size(); i++)
			{
				assetNameList.add(list.get(i).getName());
			}
		}
		else if (str.equals(getString(R.string.bankAsset)))
		{
			ArrayList<BankData> list = query.getBankList();
			
			if (list == null || list.size() < 1)
			{
				linkAssetNameTextView.setText("");
				linkAssetNameTextView.setHint("통장을 추가해주세요.");
				return;
			}
			
			linkAssetNameTextView.setText(list.get(0).getName());
			
			for (int i = 0; i < list.size(); i++)
			{
				assetNameList.add(list.get(i).getName());
			}
		}
		else if (str.equals(getString(R.string.checkCardAsset)))
		{
			ArrayList<CheckData> list = query.getCheckList();
			
			if (list == null || list.size() < 1)
			{
				linkAssetNameTextView.setText("");
				linkAssetNameTextView.setHint("체크카드를 추가해주세요.");
				return;
			}
			
			linkAssetNameTextView.setText(list.get(0).getName());
			
			for (int i = 0; i < list.size(); i++)
			{
				assetNameList.add(list.get(i).getName());
			}
		}
		else if (str.equals(getString(R.string.creditCardAsset)))
		{
			ArrayList<CreditData> list = query.getCreditList();
			
			if (list == null || list.size() < 1)
			{
				linkAssetNameTextView.setText("");
				linkAssetNameTextView.setHint("신용카드를 추가해주세요.");
				return;
			}
			
			linkAssetNameTextView.setText(list.get(0).getName());
			
			for (int i = 0; i < list.size(); i++)
			{
				assetNameList.add(list.get(i).getName());
			}
		}
		else if (str.equals(getString(R.string.phoneAsset)))
		{
			ArrayList<PhoneData> list = query.getPhoneList();
			
			if (list == null || list.size() < 1)
			{
				linkAssetNameTextView.setText("");
				linkAssetNameTextView.setHint("핸드폰을 추가해주세요.");
				return;
			}
			
			linkAssetNameTextView.setText(list.get(0).getName());
			
			for (int i = 0; i < list.size(); i++)
			{
				assetNameList.add(list.get(i).getName());
			}
		}
		else if (str.equals(getString(R.string.giftCardAsset)))
		{
			ArrayList<GiftData> list = query.getGiftList();
			
			if (list == null || list.size() < 1)
			{
				linkAssetNameTextView.setText("");
				linkAssetNameTextView.setHint("상품권을 추가해주세요.");
				return;
			}
			
			linkAssetNameTextView.setText(list.get(0).getName());
			
			for (int i = 0; i < list.size(); i++)
			{
				assetNameList.add(list.get(i).getName());
			}
		}
	}
	
	private void setRealMoneyNameData()
	{
		DBSelectQuery query = new DBSelectQuery(superContext, superDb);
		
		realMoneyNameList = new ArrayList<String>();
		
		ArrayList<RealData> list = query.getRealList();
		
		if (list == null || list.size() < 1)
		{
			realMoneyNameTextView.setText("");
			realMoneyNameTextView.setHint("현금을 추가해주세요.");
			return;
		}
		
		realMoneyNameTextView.setText(list.get(0).getName());
		
		for (int i = 0; i < list.size(); i++)
		{
			realMoneyNameList.add(list.get(i).getName());
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		
		if (resultCode != Activity.RESULT_OK)
		{
			return;
		}
		
		if (requestCode == ASSET_CHOICE_REQUEST_CODE)
		{
			String str = data.getStringExtra(AssetChoiceActivity.ASSET_CHOICE_DATA);
			linkAssetTextView.setText(str);
			
			setAssetNameData(str);
			
		}
		else if (requestCode == ASSET_LIST_REQUEST_CODE)
		{
			String str = data.getStringExtra(AssetListActivity.ASSET_NAME_DATA);
			linkAssetNameTextView.setText(str);
		}
		else if (requestCode == REALMONEY_LIST_REQUEST_CODE)
		{
			String str = data.getStringExtra(AssetListActivity.ASSET_NAME_DATA);
			realMoneyNameTextView.setText(str);
		}
	}

	@Override
	protected void tipButton()
	{
		Intent intent = new Intent(superContext, TipInfoActivity.class);
		intent.putExtra(TipInfoActivity.TIP_ID, TipMap.TIP_AUTO_SMS_INFO);
		startActivity(intent);
	}

}
